﻿#region Copyright

// All Material Copyright © 2010 Dynamic Concepts Development Corp., All Rights Reserved.
//      Portions Copyright © 1984-2009 Dynamic Concepts Development Corp., All Rights Reserved.
// For further information please contact: SoftwareSupport@dynconcepts.com
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System;
using DynConDevCorp.OpenArch.SupportLibrary.ParallelExecution.Events;

#endregion

namespace DynConDevCorp.OpenArch.SupportLibrary.ParallelExecution.Scheduling
{
    public class ScheduledExecutionItem
    {
        #region Constructors

        public ScheduledExecutionItem(EventHandler target, DateTime originalExecutionTime) : this(target, originalExecutionTime, TimeSpan.MaxValue)
        {
        }

        public ScheduledExecutionItem(EventHandler target, TimeSpan repeatRate)
            : this(target, DateTime.MinValue, repeatRate)
        {
        }

        public ScheduledExecutionItem(EventHandler target, DateTime originalExecutionTime, TimeSpan repeatRate)
        {
            r_Target = target;
            r_OriginalExecutionTime = originalExecutionTime;
            r_RepeatRate = repeatRate;
            NextExecutionTime = r_OriginalExecutionTime == DateTime.MinValue ? DateTime.UtcNow : r_OriginalExecutionTime;
            r_ExecuteEvent.Add(InternalExecuteTarget);
        }

        #endregion

        #region Public Properies and Indexers

        public DateTime NextExecutionTime { get; internal set; }

        public DateTime OriginalExecutionTime
        {
            get { return r_OriginalExecutionTime; }
        }

        public TimeSpan RepeatRate
        {
            get { return r_RepeatRate; }
        }

        public EventHandler Target
        {
            get { return r_Target; }
        }

        #endregion

        #region Instance Fields (ReadOnly)

        private readonly ParallelEvent<EventArgs> r_ExecuteEvent = new ParallelEvent<EventArgs>();
        private readonly DateTime r_OriginalExecutionTime;

        private readonly TimeSpan r_RepeatRate;
        private readonly EventHandler r_Target;

        #endregion

        #region Public Methods

        public void Execute(Object sender, EventArgs args)
        {
            r_ExecuteEvent.Execute(sender, args);
        }

        #endregion

        #region Private Methods

        private void InternalExecuteTarget(Object sender, EventArgs args)
        {
            Target(sender, args);
        }

        #endregion
    }
}